{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\".\\\\第二节.jpg\" alt=\"姓名\">\n",
    "<h1> 司大桢期末公共题（单数）</h1>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 1.输入某年某月某日，判断这一天是这一年的第几天\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_1():\n",
    "    from datetime import datetime\n",
    "\n",
    "    def day_of_year(year, month, day):\n",
    "        date = datetime(year, month, day)\n",
    "        day_num = date.timetuple().tm_yday\n",
    "        return day_num\n",
    "\n",
    "    year = int(input(\"请输入年份: \"))\n",
    "    month = int(input(\"请输入月份: \"))\n",
    "    day = int(input(\"请输入日期: \"))\n",
    "\n",
    "    print(f\"{year}年{month}月{day}日是这一年的第{day_of_year(year, month, day)}天。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 3.判断1000中有多少个素数，并输出所有素数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_3():\n",
    "    \n",
    "    def is_prime(n):\n",
    "        if n <= 1:\n",
    "            return False\n",
    "        for i in range(2, int(n**0.5) + 1):\n",
    "            if n % i == 0:\n",
    "                return False\n",
    "        return True\n",
    "\n",
    "    def find_primes_in_range(limit):\n",
    "        primes = []\n",
    "        for num in range(2, limit + 1):\n",
    "            if is_prime(num):\n",
    "                primes.append(num)\n",
    "        return primes\n",
    "\n",
    "    limit = 1000\n",
    "\n",
    "    primes = find_primes_in_range(limit)\n",
    "    print(f\"在1到{limit}之间有{len(primes)}个素数:\")\n",
    "    print(primes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 5.利用条件运算符的嵌套来完成此题：学习成绩>=90分的同学用A表示，60-89分之间的用B表示，60分以下的用C表示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_5():\n",
    "    def get_grade(score):\n",
    "        return 'A' if score >= 90 else ('B' if 60 <= score < 90 else 'C')\n",
    "\n",
    "    try:\n",
    "        score = float(input(\"请输入学习成绩（0-100）：\"))\n",
    "        \n",
    "        if not (0 <= score <= 100):\n",
    "            print(\"分数必须在0到100之间。\")\n",
    "        else:\n",
    "            grade = get_grade(score)\n",
    "            print(f\"分数: {score}, 等级: {grade}\")\n",
    "    except ValueError:\n",
    "        print(\"输入无效，请输入一个数字。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 7.输入一行字符串，分别统计出其中英文字母、空格、数字和其它字符的个数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_7():\n",
    "    def count_characters(input_string):\n",
    "        letters = 0\n",
    "        spaces = 0\n",
    "        digits = 0\n",
    "        others = 0\n",
    "\n",
    "        for char in input_string:\n",
    "            if char.isalpha():\n",
    "                letters += 1\n",
    "            elif char.isspace():\n",
    "                spaces += 1\n",
    "            elif char.isdigit():\n",
    "                digits += 1\n",
    "            else:\n",
    "                others += 1\n",
    "\n",
    "        return letters, spaces, digits, others\n",
    "\n",
    "    input_string = input(\"请输入一行字符串：\")\n",
    "\n",
    "    letters, spaces, digits, others = count_characters(input_string)\n",
    "\n",
    "    print(f\"英文字母个数: {letters}\")\n",
    "    print(f\"空格个数: {spaces}\")\n",
    "    print(f\"数字个数: {digits}\")\n",
    "    print(f\"其他字符个数: {others}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 9.一个数如果恰好等于它的因子之和，这个数就称为“完数”。例如6=1＋2＋3.编程，找出1000以内的所有完数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_9():\n",
    "    def find_perfect_numbers(limit):\n",
    "        perfect_numbers = []\n",
    "        for num in range(1, limit + 1):\n",
    "            factors_sum = sum(i for i in range(1, num) if num % i == 0)\n",
    "            if factors_sum == num:\n",
    "                perfect_numbers.append(num)\n",
    "        return perfect_numbers\n",
    "\n",
    "    limit = 1000\n",
    "\n",
    "    perfect_numbers = find_perfect_numbers(limit)\n",
    "    print(f\"1到{limit}之间的完数有：{perfect_numbers}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 11.输入任意数N，求1+2!+3!+...+N!的值（注意实数范围）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_11():\n",
    "    def factorial(n):\n",
    "        if n == 0 or n == 1:\n",
    "            return 1\n",
    "        else:\n",
    "            return n * factorial(n - 1)\n",
    "\n",
    "    def sum_of_factorials(N):\n",
    "        total = 0\n",
    "        for i in range(1, N + 1):\n",
    "            total += factorial(i)\n",
    "        return total\n",
    "\n",
    "    try:\n",
    "        N = int(input(\"请输入一个正整数N：\"))\n",
    "        if N < 0:\n",
    "            raise ValueError(\"N必须是一个非负整数。\")\n",
    "        \n",
    "        result = sum_of_factorials(N)\n",
    "        print(f\" 阶乘结果为{result}\")\n",
    "    except ValueError as e:\n",
    "        print(f\"输入无效：{e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 13.输入任意奇数N，按如下要求打印出图案（菱形）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_13():\n",
    "    def print_diamond(N):\n",
    "        \"\"\"打印一个由奇数N控制的菱形图案\"\"\"\n",
    "        if N % 2 == 0:\n",
    "            print(\"N必须是一个奇数。\")\n",
    "            return\n",
    "        \n",
    "        \n",
    "        for i in range(1, N + 1):\n",
    "            if i <= (N + 1) // 2: \n",
    "                stars = 2 * i - 1\n",
    "            else:\n",
    "                stars = 2 * (N - i + 1) - 1 \n",
    "            \n",
    "            spaces = (N - stars) // 2\n",
    "            \n",
    "            print(' ' * spaces + '*' * stars)\n",
    "\n",
    "    try:\n",
    "        N = int(input(\"请输入一个奇数N：\"))\n",
    "        if N <= 0 or N % 2 == 0:\n",
    "            raise ValueError(\"N必须是一个正奇数。\")\n",
    "        \n",
    "        print_diamond(N)\n",
    "    except ValueError as e:\n",
    "        print(f\"输入无效：{e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 15.对10个数进行排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_15():\n",
    "    import random\n",
    "\n",
    "    numbers = [random.randint(1, 100) for _ in range(10)]\n",
    "\n",
    "    print(\"原始数字列表:\", numbers)\n",
    "\n",
    "    sorted_numbers = sorted(numbers)\n",
    "    print(\"使用sorted()函数排序后的列表:\", sorted_numbers)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 17.有一个已经排好序的数组（元素数量大于10）。从键盘任意输入一个数，要求按原来的规律将它插入数组中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_17():\n",
    "    def insert_sorted_optimized(arr, num):\n",
    "\n",
    "        insert_point = next((i for i, x in enumerate(arr) if x > num), len(arr))\n",
    "        return arr[:insert_point] + [num] + arr[insert_point:]\n",
    "\n",
    "    sorted_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]\n",
    "    num_to_insert = int(input(\"请输入一个整数，将会把它插入到已排序的数组中: \"))\n",
    "    new_sorted_array = insert_sorted_optimized(sorted_array, num_to_insert)\n",
    "    print(\"插入后的新数组：\", new_sorted_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 19.有n个人围成一圈，顺序排号。从第一个人开始报数（从1到3报数），凡报到3的人退出圈子，问最后留下的是原来第几号的那位"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def question_19():\n",
    "    def josephus_problem(n, k):\n",
    "\n",
    "        people = list(range(1, n + 1))\n",
    "        \n",
    "        step = k - 1\n",
    "        \n",
    "        while len(people) > 1:\n",
    "            index_to_remove = step % len(people)\n",
    "            \n",
    "            people.pop(index_to_remove)\n",
    "        \n",
    "        return people[0]\n",
    "\n",
    "    n = 10  \n",
    "    k = 3   \n",
    "    result = josephus_problem(n, k)\n",
    "    print(f\"最后留下的是原来第{result}号的那位。\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2005年8月20日是这一年的第232天。\n"
     ]
    }
   ],
   "source": [
    "choice = input(\"请输入对应题目的数字（1、3、5、7、9、11、13、15、17、19）：\")\n",
    "if choice == \"1\":\n",
    "    question_1()\n",
    "elif choice == \"3\":\n",
    "    question_3()\n",
    "elif choice == \"5\":\n",
    "    question_5()\n",
    "elif choice == \"7\":\n",
    "    question_7()\n",
    "elif choice == \"9\":\n",
    "    question_9()\n",
    "elif choice == \"11\":\n",
    "    question_11()\n",
    "elif choice == \"13\":\n",
    "    question_13()\n",
    "elif choice == \"15\":\n",
    "    question_15()\n",
    "elif choice == \"17\":\n",
    "    question_17()\n",
    "elif choice == \"19\":\n",
    "    question_19()\n",
    "else:\n",
    "    print(\"请输入正确题目对应的数字来选择题目。\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
